package com.itany.mybatis.sql;

import com.itany.mybatis.entity.Hero;

import java.util.ArrayList;
import java.util.List;

/**
 * Description: 类的描述
 * Author: liudaolin@itany.com
 * Date: 2021/07/21 10:24
 * Version: 1.0 版本信息
 */
public class SelectHeroSql1 {

    // 可以接收 mapper 方法 调用者 传递的 参数
    public String getSql(Hero hero) {
        System.out.println("------------------------------");
        StringBuffer buffer = new StringBuffer();
        buffer.append(" select id, name, typeId from t_hero ");

        System.out.println("getSql:" + hero);

        // 存储 条件
        List<String> conditions = new ArrayList<>();
//        buffer.append(" where 1 = 1 ");
        if(null != hero.getId()){
//            buffer.append(" and id = #{id} ");
            conditions.add(" id = #{id} ");
        }
        if(null != hero.getName() && !"".equals(hero.getName())){
            // 修改参数值
            hero.setName( "%" + hero.getName() + "%" );
//            buffer.append(" and name like #{name} ");
            conditions.add(" name like #{name} ");
        }
        if(null != hero.getTypeId()){
//            buffer.append(" and typeId = #{typeId} ");
            conditions.add(" typeId = #{typeId} ");
        }

        // 有参数时, 需要 where
        // 每一个条件之间 用 and 拼接
        if(!conditions.isEmpty()){
            buffer.append(" WHERE ");
            String conditionString = String.join(" AND ", conditions);
            buffer.append(conditionString);
        }
        return buffer.toString();
    }

}
